/*

Copyright (c) 2021 唐佐林
WeChat : delphi_tang
EMail: delphi_tang@dt4sw.com

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdarg.h>
#include "app_utils.h"
#include "utils_file.h"

#define MODE_FILE  "mode"
#define WIFI_FILE  "wifi"
#define ERROR_FILE "error"

static char* ReadFile(const char* fn, char* buf, size_t size)
{
    char* ret = NULL;
    int fd = UtilsFileOpen(fn, O_RDONLY_FS, 0);

    if( (fd != -1) && (UtilsFileRead(fd, buf, size) != -1) )
    {
        ret = buf;

        UtilsFileClose(fd);
    }

    return ret;
}

static int WriteFile(const char* fn, int n, ...)
{
    int ret = 0;
    int fd = UtilsFileOpen(fn, O_CREAT_FS | O_TRUNC_FS | O_WRONLY_FS, 0);

    if( fd != -1 )
    {
        int i = 0;
        va_list vlist = {0};

        va_start(vlist, n);

        for(i=0; i<n; i++)
        {
            char* s = va_arg(vlist, char*);
            
            if( s )
            {
                ret += (UtilsFileWrite(fd, s, strlen(s) + 1) != -1) ? 0 : -1;
            }
        }

        va_end(vlist);

        UtilsFileClose(fd);
    }
    else
    {
        ret = -1;
    }

    return ret;
}

void LastError(const char* err)
{
    if( err )
    {
        WriteFile(ERROR_FILE, 1, err);
    }

}

void ClearError(void)
{
    UtilsFileDelete(ERROR_FILE);
}

char* GetError(void)
{
    static char s_buf[128] = {0};

    return ReadFile(ERROR_FILE, s_buf, sizeof(s_buf));
}

char* GetMode(void)
{
    static char s_buf[16] = {0};

    return ReadFile(MODE_FILE, s_buf, sizeof(s_buf));;
}

int SetMode(const char* mode)
{
    int ret = 0;
    
    if( mode )
    {
        ret = WriteFile(MODE_FILE, 1, mode);
    }
    else
    {
        ret = -1;
    }

    return ret;
}

int GetWifiInfo(char** id, char** pwd)
{
    static char s_buf[64] = {0};

    if( ReadFile(WIFI_FILE, s_buf, sizeof(s_buf)) )
    {
        *id = s_buf;
        *pwd = s_buf + strlen(s_buf) + 1;
    }
    else
    {
        *id = "Py4OH-Test";
        *pwd = "12345678";
    }

    return 0;
}

int SetWifiInfo(const char* id, const char* pwd)
{
    int ret = 0;

    if( id && pwd )
    {
        ret = WriteFile(WIFI_FILE, 2, id, pwd);
    }
    else
    {
        ret = -1;
    }

    return ret;
}